#include "xtest_client.h"
#include "XTools.h"
#include <thread>
#include <sstream>
#include <protobuf/xmsg_com.pb.h>
#include <XMsg.h>
#include <sstream>
#include <chrono>
void XTestClient::connectedCB()
{
    XCOM_LOG_DEBUG("connectCB");
}

bool XTestClient::GetDir(const std::string &path)
{
    if (!AutoConnect(300))
    {
        return false;
    }
    // 发送pb消息给服务器
    xmsg::XDirReq req;
    req.set_path(path);
    xmsg::XMsgHead head;
    head.set_msg_type(xmsg::MsgType::MSG_DIR_REQ);
    head.set_msg_size(req.ByteSizeLong());
    head.set_service_name("dir");
    head.set_token("dir");
    return this->SendMsg(&head, &req);
}

void XTestClient::DirRes(xmsg::XMsgHead *head, const XMsg *message)
{
    XCOM_LOG_DEBUG("XTestClient::DirRes");
    static int count = 0;
    xmsg::XDirRes res;
    if (!res.ParseFromArray(message->data, message->recv_size))
    {
        XCOM_LOG_DEBUG("res.ParseFromArray");
        return;
    }
    const google::protobuf::RepeatedPtrField<xmsg::XDirRes_XDir> &dirs = res.dirs();
    std::cout<<"    count = "<<count++<<std::endl;
    // std::cout << "    filename:" << dirs[0].filename() << std::endl;
    // std::cout << "    filetype:" << dirs[0].filetype() << std::endl;
    // std::cout << "    fileuser:" << dirs[0].fileuser() << std::endl;
    // std::cout << "    filegroup:" << dirs[0].filegroup() << std::endl;
    // std::cout << "    filelink:" << dirs[0].filelink() << std::endl;
    // std::cout << "    filesize:" << dirs[0].filesize() << std::endl;
    // std::cout << "    filetime:" << dirs[0].filetime() << std::endl;
}

bool XTestClient::AutoConnect(int timeout_ms)
{
    // 1 已经连接
    if (isConnected())
    {
        XCOM_LOG_DEBUG("isConnected");
        return true;
    }
    // 2 未连接，未在连接中
    if (!isConnecting())
    {
        // 开始连接
        if (!connect())
        {
            XCOM_LOG_DEBUG("!connect()");
            return false;
        }
    }
    // 3 连接中，等待连接完成
    int count = timeout_ms / 10;
    for (size_t i = 0; i < count; i++)
    {
        if (isConnected())
            return true;
        if (!isConnecting())
            break;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    return isConnected();
}
